<?php

/**
 * By Abduahad
 * 2017.01.01 1:09 PM
 */

namespace App\Http\Controllers\Admin;

use App\Model\UserModel;
use App\User;


use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

require_once 'resources/org/code/Code.class.php';
class LoginController extends CommonController
{
    // 后台首页
    public  function  index(){

        if($all = Input::all()){
          $code = new \Code();
          $codeRes = $code->get();
          if ($all['code'] != $codeRes){
             return back()->with('msg','驗證碼錯誤');
          }

          $user = new UserModel();
          $userInfo = $user->where('username',$all['username'])->first();
          if($userInfo != null){

            if(decrypt($userInfo->password) == $all['password']){
                session(['admin_user'=>$userInfo]);

                return redirect("Admin/index");
            }else{
                return back()->with('msg','密碼錯愕');
            }
          }else{
              return back()->with('msg','用戶不存在');
          }

        }else {
            return view("admin.login.index");
        }
    }

    // 獲取二維碼
    public function code()
    {
        $code = new \Code();
        $code->make();
    }

    // 退出
    public function quit(){
        session(['session'=>null]);
        return redirect("Admin/login");
    }

    // 密碼修改
    public function password(){
        $err = null;
        if($input = Input::all()){
            $err = $input;
        }

        return view("admin.login.password",compact('err'));
    }

    // 密碼修改提交并操作
    public function passUpdate()
    {
        //session_destroy();

        if($all = Input::all()){

            $rules = [
                'password'=>'required|between:6,20|confirmed',
            ];

            $message = [
                'password.required'=>'新密码不能为空',
                'password.between'=>'密码长度为6-20',
                'password.confirmed'=>'两次密码不一致'
            ];

            $validator =  Validator::make($all,$rules,$message);

          if($validator->passes()){
             $user = UserModel::find(session('admin_user')->user_id);
             if($all['password_o']==decrypt($user->password)){
               $user->password = encrypt($all['password']);
               $user->save();
               return redirect("Admin/info?info=修改成功");
             }else{
                 return redirect("Admin/password?err0=原始密碼錯誤");
             }
          }else{
              $url = "Admin/password?";
              $err =  $validator->errors()->all();
              foreach ($err as $k => $v){
                $url .="err".$k."=".$v."&";
              }
              return redirect($url);
          }
        }
    }

}
